package com.youlu.campus.service.activity.impl;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.common.utils.ExcelUtil;

import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityManualFeedInfo;
import com.youlu.campus.entity.VO.req.ActivityFeedImport;
import com.youlu.campus.service.activity.ActivityManualFeedInfoService;
import com.youlu.campus.service.activity.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ActivityManualFeedInfoServiceImpl implements ActivityManualFeedInfoService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private String VISITOR_PAY_FEED_PEFIX = "youlu:runtime:visitor:activity:pay-feed:userId:%s:activityId:%s";

    @Override
    public List<ActivityManualFeedInfo> getFeedInfo(String activityId, Integer page) {
        log.info(":>>> 开始获取活动Feed:{},{},{}", activityId, page);
        Query query = new Query().addCriteria(Criteria.where("activityId").is(activityId));
        query.skip((page - 1) * 10);
        query.limit(1000);
//        query.with(Sort.by(
//                Sort.Order.desc("priority")
//        ));
        List<ActivityManualFeedInfo> datas = mongoTemplate.find(query, ActivityManualFeedInfo.class);
        log.info(":>>> activityId:{},page:{}", activityId, page);
        return datas;
    }

    @Override
    public boolean delete(String activityId) {
        Query query = new Query().addCriteria(Criteria.where("activityId").is(activityId));
        mongoTemplate.remove(query, ActivityManualFeedInfo.class);
        return true;
    }

    @Override
    public boolean addAll(List<ActivityManualFeedInfo> datas) {
        mongoTemplate.insertAll(datas);
        return true;
    }

    @Override
    public Map<String, Object> Import(byte[] inputStream, String fileName, String activityId) {
        log.info(":>>> 导入活动收款Feed流 {}", fileName);
        ActivityInfo activityInfo = activityService.findOne(activityId);
        Date date = new Date();
        if (Objects.isNull(activityInfo)) {
            log.error(":>>> 活动不存在:{}", activityId);
            throw new BusinessException("活动不存在");
        }
        try {
            Map<String, Object> result = new HashMap<>();
            List<ActivityFeedImport> models = ExcelUtil.readData(new ByteArrayInputStream(inputStream), ActivityFeedImport.class);
            result.put("allCount", models.size());
            int matchCount = 0;
            int notMatchCount = 0;
            int errorInfo = 0;
            List<Integer> notMatchRows = new ArrayList<>();
            for (int i = 0; i < models.size(); i++) {
                ActivityFeedImport model = models.get(i);
                log.info(":>>> 行:{} 活动Feed流 {} 提示语", i, model.getUniversityName(), model.getName());
                if (StringUtils.isBlank(model.getUniversityName()) || StringUtils.isBlank(model.getName())) {
                    log.error(":>>> 导入参数错误:大学、名字为空");
                    errorInfo++;
                    continue;
                }
                ActivityManualFeedInfo feedInfo = new ActivityManualFeedInfo();
                feedInfo.setActivityId(activityId);
                feedInfo.setActivityStatus(1);
                feedInfo.setContent(model.getUniversityName() + " " + model.getName() + "已领取");
                feedInfo.setCreatedTime(date);
                feedInfo.setPriority(model.getPriority());
                matchCount++;
                mongoTemplate.insert(feedInfo);
            }
            result.put("matchCount", matchCount);
            result.put("notMatchCount", notMatchCount);
            result.put("notMatchRows", notMatchRows);
            result.put("errorInfo", errorInfo);
            result.put("tips", "列序号从0(A列)开始,第1列订单编号(A列)、第2列(B列)提示语不能为空!");
            return result;
        } catch (Exception e) {
            log.error(":>>> 活动收款Feed流导入 error fileName {},{}", fileName, e);
            return null;
        }
    }

    @Override
    public Integer getVisitorFeedPage(String userId, String activityId) {
        String key = getVisitorFeedPageKey(userId, activityId);
        Object v = redisTemplate.opsForValue().get(key);
        if (Objects.isNull(v)) {
            log.info(":>>> 用户:{} 活动:{} 暂无Feed流访问记录", userId, activityId);
            return null;
        }
        log.info(":>>> 用户:{} 活动:{} Feed流访问记录:{}", userId, activityId, v);
        return (Integer) v;
    }

    @Override
    public void setVisitorFeedPage(String userId, String activityId, Integer page) {
        String key = getVisitorFeedPageKey(userId, activityId);
        redisTemplate.opsForValue().set(key, page+"", 7, TimeUnit.DAYS);
    }

    @Override
    public Long total(String activityId) {
        Query query = new Query().addCriteria(Criteria.where("activityId").is(activityId));
        return mongoTemplate.count(query, ActivityManualFeedInfo.class);
    }

    /**
     * 获取访客Feed流前缀Key
     *
     * @param userId
     * @param activityId
     * @return
     */
    private String getVisitorFeedPageKey(String userId, String activityId) {
        return String.format(VISITOR_PAY_FEED_PEFIX, userId, activityId);
    }
}
